package likou;

import java.util.Arrays;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/17 08:35
 */
public class _1030 {
    public static void main(String[] args) {
        int [][] daan = allCellsDistOrder2(2,2,0,1);
        for (int[] is:daan){
            System.out.println(Arrays.toString(is));
        }
    }
    public static int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
        int [][] daan = new int[R*C][2];
        int index = 0;
        for (int i=0;i<R;i++){
            for (int j=0;j<C;j++){
                daan[index] = new int[]{i,j};
                index++;
            }
        }
        Arrays.sort(daan, (o1, o2) -> Math.abs(r0-o1[0])+Math.abs(c0-o1[1])-Math.abs(r0-o2[0])-Math.abs(c0-o2[1]));
        return daan;
    }
    public static int[][] allCellsDistOrder2(int R, int C, int r0, int c0) {
        int[][] re = new int[R * C][2];
        int dist = 0;
        int cnt = 0;
        int[] factor = {-1, 1};
        while (cnt < R * C) {
            for (int rowDist = 0; rowDist <= dist; rowDist++) {
                int colDist = dist - rowDist;
                for (int i = 0; i < 2; i++) {
                    int row = r0 + factor[i] * rowDist;
                    for (int j = 0; j < 2; j++) {
                        int col = c0 + factor[j] * colDist;
                        if (row >= 0 && row < R && col >= 0 && col < C) {
                            re[cnt][0] = row;
                            re[cnt][1] = col;
                            cnt++;
                        }
                        if (colDist == 0) {
                            break;
                        }
                    }
                    if (rowDist == 0) {
                        break;
                    }
                }
            }
            dist++;
        }
        return re;
    }
}
